package com.simplenix.nicasio.def;

import com.simplenix.nicasio.misc.AppException;
import com.simplenix.nicasio.misc.StrUtil;
import com.simplenix.nicasio.misc.XMLUtil;
import com.simplenix.nicasio.sys.SystemDef;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;

/**
 *
 * @author fronald
 */
public class Modules {

	private static Modules modules = null;

	private List<Module> modsList;

	public static Modules getInstance(String appPath) throws AppException {
		if (modules == null) {
			modules = new Modules(appPath);
		}
		return modules;
	}

	public List<Module> getModulesList() {
		return new ArrayList<Module>(modsList);
	}

	private Modules(String appPath) throws AppException {
		try {
			this.modsList = new ArrayList();
			Module module = new Module();
			module.setBasePackage(null);
			module.setName("nicasio");
			module.setVendor("SimpleNIX Open Systems");
			module.setVersion(null);
			this.modsList.add(module);
			Document doc = XMLUtil.fileToXml(new File(appPath + "/WEB-INF/config/modules.xml"));
			Element mods = doc.getRootElement();
			List<Element> modList = mods.elements();
			for (Element mod : modList) {
				module = new Module();
				String basePackage = StrUtil.nvl(mod.attributeValue("basepackage"));
				String version = StrUtil.nvl(mod.attributeValue("version"));
				String name = StrUtil.nvl(mod.attributeValue("name"));
				String vendor = StrUtil.nvl(mod.attributeValue("vendor"));
				if (!basePackage.equals("") && !version.equals("") && !name.equals("")) {
					module.setBasePackage(basePackage);
					module.setName(name);
					module.setVendor(vendor);
					module.setVersion(version);
					this.modsList.add(module);
				} else {
					throw new AppException("Not valid module(s)");
				}
			}
		} catch (Exception e) {
			throw new AppException(e);
		}
	}

	public Features getFeaturesByModule(Module module) throws AppException {
		return new Features(module);

	}

	public Module getModuleByName(String moduleName) throws AppException {
		for (Module module : this.modsList) {
			if (module.getName().equals(moduleName)) {
				return module;
			}
		}
		return null;
	}

}
